package com.edais.actions;

import com.alibaba.fastjson.JSONObject;
import com.edais.domain.IpLogBean;
import com.edais.domain.RiskEvaluation;
import com.edais.domain.User;
import com.edais.domain.WeixinMediaBinding;
import com.edais.log.IpLog;
import com.edais.service.*;
import com.edais.util.*;
import com.edais.util.weixinAbout.SendWeiXinUtil;
import com.yunzhi.domain.RequestHeader;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import com.yunzhi.util.RequestUtil;
import com.yunzhi.util.ResponseUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 活期接口
 */
@Controller
@RequestMapping("/wxenjoy")

public class WxEnjoyAction  implements Serializable{

	private static final long serialVersionUID = 1L;

	private static final Log logger = LogFactory.getLog(WxEnjoyAction.class);

	@Autowired
	private WxEnjoyService wxEnjoyService;
	
	@Autowired
	private EnjoyService enjoyService;
	
	@Autowired
	private CenterService centerService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private CaptchaService captchaService;
	
	@Autowired
	private WeixinBindingService weixinBindingService;
	
	@Autowired
	private SMSService sMSService;
	
	@Autowired
	private WeixinEnjoyService weixinEnjoyService;
	@Autowired
	private TurnOutService turnOutService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private RiskEvaluationService riskEvaluationService;


	/**
	 * 活期购买接口（原优享计划）
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/buyEnjoyPlan")
	public void buyEnjoyPlan(HttpServletRequest request, HttpServletResponse response) throws Exception{
        if (!RequestUtil.validSign(request)) {
            logger.info("无效签名");
            ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
            return;
        }
        if (!RequestUtil.validToken(request)) {
            logger.info("无效token");
            ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
            return;
        }
        RequestHeader header = RequestUtil.decodeHeader(request);
        JSONObject paramMap = RequestUtil.decodeDataJson(request);
        Map<String, Object> jsonMap = new HashMap<String, Object>();
		String userId = String.valueOf(header.getUserId());
        paramMap.put("userId",userId);
		String buyAmount = paramMap.getString("buyAmount");
		String ip = CommonUtil.getClientIP(request);
		IpLogBean logBean = new IpLogBean();
		logBean.setIp(ip);
		logBean.setAction("活期购买");
		logBean.setUser(userId);
		logBean.setStatus(Consts.ERROR_CN);
		logBean.setDetail(userId+"进行了活期购买操作");
		Map resMap = new HashMap<String,Object>();
		ResultDTO checkMap = joinCheck(paramMap);
		if (null == checkMap || checkMap.codeEq(ResultCode.FAILED)) {
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			ResponseUtil.write(response, checkMap);
			return;
		}
		BigDecimal decBuyAmount = new BigDecimal(buyAmount);// 购买金额
		//投资金额的上下限检查
		String minInvestMoneyz=userService.getSystemSettingValue("ysjs_gmqtje_value");
		BigDecimal minInvestMoney = new BigDecimal((null==minInvestMoneyz||"".equals(minInvestMoneyz))?"0":minInvestMoneyz);//最小投资金额
		if((null != minInvestMoney && CommonUtil.checkAmount(decBuyAmount, minInvestMoney) < 0) ||
			(decBuyAmount.compareTo(BigDecimal.valueOf(0.00))==0)){
			//最小投资金额
			logger.info("购买活期时购买金额低于最小投资金额，购买金额:" + decBuyAmount);
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.BUYAMOUNT_BELOW_MINAMOUNT));
			return;
		}
		// 开关控制最大金额 by ouyy
		String kgValue=userService.getSystemSettingValue("ysjs_gmzded_kg_value");//活期-购买最大额度-开关 0-表示关　1-表示开
		if("1".equals(kgValue)){
			String maxBuyerAmountz=userService.getSystemSettingValue("ysjs_gmzded_value");
			Map<String,String> reOrMap=new HashMap<String,String>();
			reOrMap.put("type", "107");
			reOrMap.put("userId", userId);
			String investAmount=orderService.getOrderInvestAmountForEnjoy(reOrMap);
			BigDecimal maxBuyerAmount = new BigDecimal((null==maxBuyerAmountz||"".equals(maxBuyerAmountz))?"0":maxBuyerAmountz);//投资最大金额
			BigDecimal buyAmountBig=new BigDecimal(buyAmount).add(new BigDecimal(investAmount));//购买金额加订单金额
			logger.info("允许购买活期总额:"+maxBuyerAmountz);
			logger.info("活期购买金额:"+buyAmount);
			logger.info("活期订单购买总额:"+investAmount);
			if(CommonUtil.checkAmount(buyAmountBig, maxBuyerAmount) > 0){
				//购买最大金额
				logger.info("亲爱的用户，您的活期账户投资金额不能超过"+maxBuyerAmountz+"元");
				ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,"亲爱的用户，您的活期账户投资金额不能超过"+maxBuyerAmountz+"元"));
				return;
			}
		}
		// 获取该用户的余额
		Map<String, Object> pageMode = new HashMap<String, Object>();
		pageMode.put("userId", userId);
		String acctBalance = "0.00";// 余额
		resMap = centerService.getCusBalance(pageMode);
		if (resMap != null && "00000".equals(resMap.get("rescode"))) {
			acctBalance = resMap.get("ACCTBALANCE") + "";
		} else {
			logger.info("购买活期调用核心E300012失败:" + resMap.get("resmsg"));
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.BUSINESSE_ERROR));
			return;
		}
		// 余额检查
		if ("0.00".equals(acctBalance) || StringUtils.isBlank(acctBalance)) {
			logger.info("购买活期时余额不足,余额为:" + acctBalance);
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.BALANCE_IS_NOT_SUFFICIENT));
			return;
		}
		BigDecimal decBalance = new BigDecimal(acctBalance);// 余额
		// 余额-理财计划金额 < 0
		if (decBalance.compareTo(decBuyAmount) < 0) {
			logger.info("购买活期时余额不足,余额差:" + (decBalance.subtract(decBuyAmount)));
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.BALANCE_IS_NOT_SUFFICIENT));
			return;
		}
		pageMode.put("userId", userId);
		pageMode.put("investmentAmount", buyAmount);
		pageMode.put("buyMedia","2");
		Map retMap = wxEnjoyService.dealBuyDepositGetByBalance(pageMode);
		if(retMap == null){
			if(StringUtils.isNotBlank(ip)){
				IpLog.printIpLog(logBean);
			}
			ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.BUSINESSE_ERROR));
			return;
		}else{
			if(!Consts.SUCCESS_CODE.equals((String)retMap.get("rescode"))){
				ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.BUSINESSE_ERROR));
				return;

			}else{
				jsonMap.put("orderId", retMap.get("orderId"));
			}
		}
		logBean.setStatus(Consts.SUCCESS_CN);
		IpLog.printIpLog(logBean);
		String result = JsonUtil.getJsonStringFromMap(jsonMap);
		//ouyy 活期投资成功发送短信
		if(Consts.SUCCESS_CODE.equals(retMap.get("rescode"))){
			//推送购买微信/短信接口
			sendMeidaAndSMS(userId,paramMap, buyAmount);
		}
		// 处理返回结果
		ResultDTO<String> resultDTO = new ResultDTO<>(ResultCode.SUCCESS);
		resultDTO.setRecord(result);
		ResponseUtil.write(response,  resultDTO);
	}

    /**
     * 购买活期数据检查
     * @param paramsMap
     * @return
     * @throws Exception
     */
	private ResultDTO joinCheck(JSONObject paramsMap) throws Exception{
		Map<String, String> resMap = new HashMap<String,String>();
		// 用户id
		String userId = paramsMap.getString("userId");
		// 购买理财计划金额
		String buyAmount = paramsMap.getString("buyAmount");
		// 交易密码
		String passwordCash = paramsMap.getString("passwordCash");

		// 用户id
		if (StringUtils.isBlank(userId)) {
			logger.error("购买活期数据检查失败： 用户id为空");
            return new ResultDTO(ResultCode.FAILED, "购买活期数据检查失败： 用户id为空");
		}

		// 购买金额检查（必须是100元以上,且小数点后2位）
		boolean flag = buyAmount.matches("^[0-9]*[\\.]{0,1}[0-9]{0,2}$");
		if (!flag) {
			logger.error("购买活期时输入的购买金额非法，购买金额:" + buyAmount);
            return new ResultDTO(ResultCode.FAILED, Message.CnDescriptionExpression.BUYAMOUNT_IS_NON_STANDARD);
		}
		// 购买金额
		if (StringUtils.isBlank(buyAmount)) {
			logger.error("购买活期数据检查失败： 购买金额是:" + buyAmount);
            return new ResultDTO(ResultCode.FAILED, Message.CnDescriptionExpression.AMOUNT_IS_NULL);
		}

		// 交易密码验证
		if (StringUtils.isBlank(passwordCash)) {
			logger.error("购买活期数据检查失败：交易密码为空");
            return new ResultDTO(ResultCode.FAILED, "交易密码不能为空!");
		}

        User user = userService.getUserDetail(userId);
        String passwordMd5 = MD5.md5(passwordCash);
        if (!passwordMd5.equals(user.getPassword_cash())) {
            logger.error("购买活期数据检查失败：交易密码错误，请重新输入！");
            return new ResultDTO(ResultCode.FAILED, "交易密码错误，请重新输入！");
        }

		/** 获取用户是否实名认证,对于实名认证用户取得身份证号和姓名 */
		// 判断用户是否实名认证
		if (!"1".equals(user.getIs_create_acct()) || !"Y".equals(user.getIdcard_validate())) {
			logger.error("购买活期数据检查失败：用户没有经过实名认证");
            return new ResultDTO(ResultCode.FAILED, Message.CnDescriptionExpression.AUTHENTICATION_IS_NOT);
		}

		// 活期投资的时间限制
		DateFormat df = new SimpleDateFormat("HH:mm:ss");// 24小时制
		Date dt1 = df.parse("23:00:00");
		Date dt2 = df.parse("2:00:00");
        //获取当前数据库时间
        String timeStr = weixinEnjoyService.querySysTime();
        Date time = df.parse(timeStr);
        String timeWarn = userService.getSystemSettingValue("ENJOY_BUY_TIME_WARN");
        String[] timeWarnArr = timeWarn.split("\\|");
        if(StringUtil.isNotEmpty(timeWarn) && timeWarnArr.length > 0){
            dt1 = df.parse(timeWarnArr[0]);
            dt2 = df.parse(timeWarnArr[1]);
        }
        if(time.after(DateUtil.oneSecond(dt1, -1)) || time.before(DateUtil.oneSecond(dt2, 1))){
            logger.error("活期投资接口发生异常: 投资的时间限制外");
            return new ResultDTO(ResultCode.FAILED, Message.CnDescriptionExpression.ENJOY_BUY_TIME_WARN);
        }
        return new ResultDTO(ResultCode.SUCCESS, "");
	}
	
	/**
	 * 根据USERID发送短信/微信
	 * @param userId
	 */
	public void sendMeidaAndSMS(String userId,JSONObject paramsMap,String buyAmount) throws Exception{
		//封装用户ID
		WeixinMediaBinding mediaBinding = new WeixinMediaBinding();
		mediaBinding.setUserId(Integer.parseInt(userId));
		
		//先推送微信，微信成功不发短信，失败再发短信
		String mobile = captchaService.getMobileById(userId);//通过用户ID查询使用手机号
		String mediaUid = weixinBindingService.queryMediaUid(mediaBinding);//通过用户ID实体类查询微信标识
		
		//TODO 逻辑判断
		if(null == mediaUid || "null".equalsIgnoreCase(mediaUid) || "".equalsIgnoreCase(mediaUid)){
			logger.info("[推送短信息]因手机号："+mobile+"并未绑定微信");
			//发送短信
			String cpType="活期";
			String smsNo="sms02003";//config_sms表中参数
			String tsje=paramsMap.getString("buyAmount");
			if (StringUtils.isBlank(userId) 
					|| StringUtils.isBlank(smsNo)|| StringUtils.isBlank(tsje)) {
				logger.debug("wxenjoy/join sendSMS 传入参数为空");
			}
			try{
				// 发送短信
				if(StringUtils.isEmpty(cpType)){
					 sMSService.getSMS(userId,smsNo,tsje);	
				}else{
					sMSService.getSMS(userId,smsNo,tsje,cpType);	
				}
			} catch (Exception e) {
				logger.error("wxenjoy/join sendSMS异常:" + e.getCause());
			}
		}else{
			Map<String,String> weixinTMap = new HashMap<String,String>();
			weixinTMap.put("mediaUid", mediaUid);//微信用户唯一标识 
			weixinTMap.put("productInfo", "活期");//产品内容
			weixinTMap.put("number", buyAmount);//购买金额
			weixinTMap.put("functionScope", "buy");//购买金额
			
			boolean sendRusult = SendWeiXinUtil.sendWeiXin(weixinTMap);
			if(!sendRusult){
				logger.info("[微信推送失败][推送短信息]因手机号："+mobile+"并未绑定微信或者未关注联币钱包微信号");
				//发送短信
				String cpType="活期";
				String smsNo="sms02003";//config_sms表中参数
				String tsje=paramsMap.getString("buyAmount");
				if (StringUtils.isBlank(userId) 
						|| StringUtils.isBlank(smsNo)|| StringUtils.isBlank(tsje)) {
					logger.debug("wxenjoy/join sendSMS 传入参数为空");
				}
				try{
					// 发送短信
					if(StringUtils.isEmpty(cpType)){
						 sMSService.getSMS(userId,smsNo,tsje);	
					}else{
						sMSService.getSMS(userId,smsNo,tsje,cpType);	
					}
				} catch (Exception e) {
					logger.error("wxenjoy/join sendSMS异常:" + e.getCause());
				}
			}else{
				logger.info("[微信推送]手机号："+mobile+"推送成功");
			}
		}
	}
	
	
	/**
	 * @Description: 投资理财列表（首页）
	 * @param @param request
	 * @param @param response
	 * @return void
	 * @throws
	 * @author chenshufeng
	 * @date 2016-6-7
	 */
	@RequestMapping(value = "/getInvestList")
	public void getInvestList(HttpServletRequest request, HttpServletResponse response) throws Exception{
		//签名校验
		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}

		// 解密请求参数
		JSONObject paramMap = RequestUtil.decodeDataJson(request);

			Map<String, Object> map = new HashMap<String, Object>();
			String pageSize = (String) paramMap
					.get(Consts.Page.PAGE_SIZE_NAME);// 页码
			String current = (String) paramMap
					.get(Consts.Page.PAGE_CURRENT_NAME);// 每页行数
			if (pageSize == null || StringUtils.isBlank(pageSize)
					|| "0".equals(pageSize)) {
				pageSize = "10";
			}
			if (current == null || StringUtils.isBlank(current)
					|| "0".equals(current)) {
				current = "1";
			}

			int beginNum = (Integer.parseInt(current) - 1)
					* Integer.parseInt(pageSize) + 1;
			int endNum = Integer.parseInt(pageSize) * Integer.parseInt(current);

			map.put("rowBegin", String.valueOf(beginNum));
			map.put("rowEnd", String.valueOf(endNum));
            map.put("pageSize", pageSize);
			// 查询投资理财列表
			ResultDTO result =this.weixinEnjoyService.getInvestList(map);
			ResponseUtil.write(response, result);
	}

	/**
	 * 活期投资(首页，资产，资产详情)（原优享计划）
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/enjoyPlanProductIndex")
	public void enjoyPlanProductIndex(HttpServletRequest request, HttpServletResponse response) throws Exception{
		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		RequestHeader header = RequestUtil.decodeHeader(request);
		JSONObject paramMap = RequestUtil.decodeDataJson(request);
		// 用户id
		Long userId = header.getUserId();
		// 产品ID
		String productId = paramMap.getString("productId");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("productId", productId);
		Map<String,Object> resultMap = weixinEnjoyService.enjoyPlanProductIndex(map);
		ResultDTO<Map<String,Object>> resultDTO = new ResultDTO<>(ResultCode.SUCCESS);
		resultDTO.setRecord(resultMap);
		ResponseUtil.write(response,  resultDTO);
	}
	
	/**
	 * @Description: 保存或修改ios设备信息
	 * @param @param request
	 * @param @param response   
	 * @return void  
	 * @throws
	 * @author chenshufeng
	 * @date 2016-6-22
	 */
	@RequestMapping(value = "/saveIosDeviceInfo"/*,method=RequestMethod.GET*/)
	public void saveOrUpdateIosDeviceInfo(HttpServletRequest request,
			HttpServletResponse response) {
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		// 用户idfa
		String idfa = paramsMap.get("idfa");
		// 用户ip
		String ip = paramsMap.get("ip");
		
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("idfa", idfa);
			map.put("ip", ip);
			map.put("createrName", "");
			String result = weixinEnjoyService.saveOrUpdateIosDeviceInfo(map);
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("保存或修改ios设备信息接口异常:"
					+ CommonUtil.printStackTraceToString(e));
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
		}
	}
    /**
     * 厚钱宝详情接口数据检查
     */
    private Map<String,Object> historyProfitCheck(JSONObject paramMap) throws Exception{
        Map<String,Object> resMap = new HashMap<String,Object>();
//		String userId = paramMap.get("userId");
        String currentPageStr = paramMap.getString(Consts.Page.PAGE_CURRENT_NAME);//当前页
        String pageSizeStr = paramMap.getString(Consts.Page.PAGE_SIZE_NAME);//页大小
        Integer current = 1;
        Integer pageSize = 10;//默认显示10条
//		if(StringUtils.isBlank(userId)){
//			logger.error("厚钱宝历史收益列表接口数据检查失败：用户id为空" );
//			resMap.put("code", Consts.ERROR_CODE);
//			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
//			return resMap;
//		}

        //分页参数
        if (currentPageStr != null && !("".equals(currentPageStr))) {
            current = Integer.parseInt(currentPageStr);
        }
        if (pageSizeStr != null && !("".equals(pageSizeStr))) {
            pageSize = Integer.parseInt(pageSizeStr);
        }

        resMap.put("pageSize", pageSize);
        resMap.put("current", current);
        resMap.put("code", Consts.SUCCESS_CODE);
        resMap.put("message", Consts.SUCCESS_DESCRIBE);
        return resMap;
    }
    /**
	 * 活期转出记录，fanping
	 */
		@RequestMapping(value = "/getEnjoyPlanMoneyFundFlow")
		public void getEnjoyPlanMoneyFundFlow(HttpServletRequest request, HttpServletResponse response)
				throws Exception{
			if (!RequestUtil.validSign(request)) {
				logger.info("无效签名");
				ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
				return;
			}
			if (!RequestUtil.validToken(request)) {
				logger.info("无效token");
				ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
				return;
			}
			RequestHeader header = RequestUtil.decodeHeader(request);
			JSONObject map = RequestUtil.decodeDataJson(request);

            String userId=String.valueOf(header.getUserId());
            map.put("userId",userId);
            Map<String,Object> checkMap = historyProfitCheck(map);
            if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))){
                ResultDTO result=new ResultDTO(ResultCode.FAILED);
                return;
            }

            //调用核心查询历史记录
            ResultDTO result = turnOutService.queryTurnOutList(map);
            ResponseUtil.write(response,  result);
			return;
		}


    /**
     * 查询债券列表
     * @param request
     * @param response
     * @throws Exception
     */
	@RequestMapping(value = "/getEnjoyCreditList")
	public void getEnjoyCreditList(HttpServletRequest request, HttpServletResponse response) throws Exception{
		Integer current = 1;
		Integer pageSize = 10;

        if (!RequestUtil.validSign(request)) {
            logger.info("无效签名");
            ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
            return;
        }
        if (!RequestUtil.validToken(request)) {
            logger.info("无效token");
            ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
            return;
        }
        RequestHeader header = RequestUtil.decodeHeader(request);
        JSONObject paramMap = RequestUtil.decodeDataJson(request);

		String currentStr = paramMap.getString(Consts.Page.PAGE_CURRENT_NAME);   //当前页数
		String pageSizeStr = paramMap.getString(Consts.Page.PAGE_SIZE_NAME);     //页大小

        if(currentStr != null && !("".equals(currentStr))){
            current = Integer.parseInt(currentStr);
        }
        if(pageSizeStr != null && !("".equals(pageSizeStr))){
            pageSize = Integer.parseInt(pageSizeStr);
        }
        Map<String, String> map = new HashMap<String, String>();

        String userId = String.valueOf(header.getUserId());
        String orderId = paramMap.getString("orderId");
        map.put("current",current.toString());
        map.put("pageSize",pageSize.toString());
        map.put("userId", userId);
        map.put("orderId", orderId == null ? "" : orderId);

        //调用核心查询债券列表
        ResultDTO rtnMapString = enjoyService.queryEnjoyCreditList(map);
        ResponseUtil.write(response,rtnMapString);
	}

	/**
	 * 活期投资详情（原优享计划）
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getEnjoyBuyDetail")
	public void getEnjoyBuyDetail(HttpServletRequest request, HttpServletResponse response) throws Exception{
		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
//		if (!RequestUtil.validToken(request)) {
//			logger.info("无效token");
//			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
//			return;
//		}
		RequestHeader header = RequestUtil.decodeHeader(request);
		String userId = String.valueOf(header.getUserId());
		Map<String, String> map = new HashMap<String, String>();
		map.put("productId", "107");
		map.put("userId", StringUtil.isEmpty(userId) ? "" : userId);

		Map<String,Object> jsonMap = enjoyService.queryEnjoyBuyDetail(map);
        net.sf.json.JSONObject json = null;
		try {
			DateFormat df = new SimpleDateFormat("HH:mm:ss");// 24小时制
			String dt1 = df.format(df.parse("23:00:00"));
			String dt2 = df.format(df.parse("2:00:00"));
			// 投资的时间限制
			String timeWarn = userService.getSystemSettingValue("ENJOY_BUY_TIME_WARN");
			String[] timeWarnArr = timeWarn.split("\\|");
			if(StringUtil.isNotEmpty(timeWarn) && timeWarnArr.length > 0){
				dt1 = timeWarnArr[0];
				dt2 = timeWarnArr[1];
			}
            json = (net.sf.json.JSONObject) jsonMap.get("enjoyBuyDetail");
			json.put("enjoyBuyTimeWarn", dt2+"-"+dt1);
		} catch (Exception e) {
			logger.error("查询活期投资的时间限制",e);
			json = (net.sf.json.JSONObject) jsonMap.get("enjoyBuyDetail");
			json.put("enjoyBuyTimeWarn", "2:00:00-23:00:00");
		}

		try {//风险评估
			RiskEvaluation riskEvaluation=riskEvaluationService.getRiskEvaluationByUserId(userId);
			jsonMap.put("isRiskEvaluation",riskEvaluation.getIsRisk());
			jsonMap.put("riskType",riskEvaluation.getRiskType());
		} catch (Exception e) {
			logger.error("查询风险评估异常",e);
			jsonMap.put("isRiskEvaluation","N");
		}

		ResultDTO<net.sf.json.JSONObject> resultDTO = new ResultDTO<>(ResultCode.SUCCESS);
		resultDTO.setRecord(json);
		ResponseUtil.write(response,  resultDTO);
	}
	
	
	/**
	 * 查询标的列表
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getEnjoyLoanList")
	public void getEnjoyLoanList(HttpServletRequest request, HttpServletResponse response){
		Integer current = 1;
		Integer pageSize = 10;
		
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String currentStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);   //当前页数
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);     //页大小
		
		try{
			if(currentStr != null && !("".equals(currentStr))){
				current = Integer.parseInt(currentStr);
			}
			if(pageSizeStr != null && !("".equals(pageSizeStr))){
				pageSize = Integer.parseInt(pageSizeStr);
			}
			Map<String, Object> map = new HashMap<String, Object>();
			Map<String, Object> jsonMap = new HashMap<String, Object>();
			
			String userId = paramsMap.get("userId");
			map.put("current",current.toString());
			map.put("pageSize",pageSize.toString());
			map.put("userId", userId == null ? "" : userId);
			
			//查询标的列表
			jsonMap = this.enjoyService.queryEnjoyLoanList(map);
			
			// 处理返回结果
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查询标的信息异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, "", e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
//	/***
//	 * 活期-获取手续费抵用券
//	 * fanping
//	 */
//	@RequestMapping(value = "/getCouponList")
//	public void getCouponList(HttpServletRequest request, HttpServletResponse response) throws Exception{
//        if (!RequestUtil.validSign(request)) {
//            logger.info("无效签名");
//            ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
//            return;
//        }
//        if (!RequestUtil.validToken(request)) {
//            logger.info("无效token");
//            ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
//            return;
//        }
//
//        RequestHeader header = RequestUtil.decodeHeader(request);
//        logger.info("header：" + header.toString());
//		JSONObject paramsMap = RequestUtil.decodeDataJson(request);
//
////        logger.info("data：" + paramsMap.toString());
//
//        Map<String,Object> checkMap = historyProfitCheck(paramsMap);
//        if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))){
//
//            // 处理返回结果
//            ResponseUtil.write(response,  ResultConstant.FAILED);
//        }
//
//        Integer current = 0;
//        Integer pageSize = 10;
//        String currentStr = String.valueOf(paramsMap.get(Consts.Page.PAGE_CURRENT_NAME)); // 当前页数
//        String pageSizeStr = String.valueOf(paramsMap.get(Consts.Page.PAGE_SIZE_NAME)); // 页大小
//
//        if (currentStr != null && !("".equals(currentStr))) {
//            current = Integer.parseInt(currentStr);
//        }
//        if (pageSizeStr != null && !("".equals(pageSizeStr))) {
//            pageSize = Integer.parseInt(pageSizeStr);
//        }
//
//		paramsMap.put("rowBegin", ((current-1)*pageSize+1)+"");
//		paramsMap.put("rowEnd",current*pageSize+"");
//		paramsMap.put("userId",header.userId2String());
//        ResultDTO result = this.turnOutService.queryCouponList(paramsMap);
//		ResponseUtil.write(response, result);
//
//		logger.error("/wxenjoy/getCouponList 获取手续费抵用券 异常：");
//
//		// 处理返回结果
//		ResponseUtil.write(response,  new ResultDTO<>(ResultCode.FAILED));
//		return;
//	}

	/**
	 * @Description: 活期投资人列表信息
	 * @param request
	 * @param @param response
	 * @return void
	 * @throws
	 * @author wuhan
	 * @date 2016-6-14
	 */
	@RequestMapping(value = "/queryEnjoyTodayUserInfoList")
	public void queryEnjoyTodayUserInfoList(HttpServletRequest request,HttpServletResponse response) throws Exception{

		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}

		Map<String,Object> 	paramsMap = RequestUtil.decodeData(request); // 解密请求参数
		Integer current = 0;
		Integer pageSize = 10;
		String currentStr = String.valueOf(paramsMap.get(Consts.Page.PAGE_CURRENT_NAME)); // 当前页数
		String pageSizeStr = String.valueOf(paramsMap.get(Consts.Page.PAGE_SIZE_NAME)); // 页大小

		//分页参数
		if (currentStr != null && !("".equals(currentStr))) {
			current = Integer.parseInt(currentStr);
		}
		if (pageSizeStr != null && !("".equals(pageSizeStr))) {
			pageSize = Integer.parseInt(pageSizeStr);
		}

		// 获取标的列表信息
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("currentPage", current);
		map.put("pageSize", pageSize);

		ResultDTO resultDTO = weixinEnjoyService.queryEnjoyTodayUserInfoList(map);
		ResponseUtil.write(response,resultDTO);
	}
	
	/**
	 * @Description: 转出页面内容查询
	 * @param @param request
	 * @param @param response
	 * @return void
	 * @throws
	 * @author ouyy
	 * @date 2016-6-8
	 */
	@RequestMapping(value = "/turnOutDetail")
	public void turnOutDetail(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}
		// 解密请求参数
		RequestHeader header = RequestUtil.decodeHeader(request);
		JSONObject paramsMap = RequestUtil.decodeDataJson(request);
		Map<String, Object> map = new HashMap<String, Object>();
		if(null != paramsMap) {
			map.put("faceValue", paramsMap.getString("faceValue"));
		} else {
			map.put("faceValue","0");
		}
		Long userId = header.getUserId();   // 用户id
		map.put("userId", String.valueOf(userId));
		String result = wxEnjoyService.getTurnOutDetail(map);
		ResponseUtil.write(response,  result);
	}
	
	/**
	 * 转出接口
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/turnOut")
	public void turnOut(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logger.info("======进入方法：wxenjoy/trunOut=======");
		long a=System.currentTimeMillis();
		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}
		// 解密请求参数
		RequestHeader header = RequestUtil.decodeHeader(request);
		JSONObject paramsMap = RequestUtil.decodeDataJson(request);
		Long userId = header.getUserId();   // 用户id
		paramsMap.put("finaceId", "1");
		paramsMap.put("userId", String.valueOf(userId));
		// 数据检查
		Map<String,Object> checkMap = trunOutCheck(paramsMap);
		if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))){
			ResultDTO<String> resultDTO = new ResultDTO<>(ResultCode.FAILED, String.valueOf(checkMap.get("message")));
			// 处理返回结果
			ResponseUtil.write(response,  resultDTO);
			logger.error("paramsMap" +paramsMap);
			return;
		}
		Map<String, String> map = new HashMap<String,String>();
		map.put("userId", String.valueOf(userId));//用户ID
//		map.put("helpId", paramsMap.get("helpId"));//抵用券ID
		map.put("turnOutAmount", paramsMap.getString("turnOutAmount"));//转出金额
		map.put("passwordCash", paramsMap.getString("passwordCash"));//交易密码
//		map.put("turnOutFee", paramsMap.get("turnOutFee"));//手续费
		map.put("planId","107");//产品类型　107-活期
//		logger.info("======wxenjoy/trunOut=======userId:"+paramsMap.get("userId")+
//				"|turnOutAmount:"+paramsMap.get("turnOutAmount")+"|turnOutFee:"+paramsMap.get("turnOutFee")+
//				"|helpId:"+paramsMap.get("helpId"));
		// 转出接口
		String result = wxEnjoyService.updateInvestmentAmount(map);
		JSONObject jsonObject = JSONObject.parseObject(result);
		if("0000".equals(jsonObject.getString("resCode"))){
			logger.info(paramsMap.get("userId")+"转出成功"+paramsMap.get("turnOutAmount"));
		}
		ResponseUtil.write(response,  result);
		System.out.println("wxenjoy/trunOut接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
		logger.error("wxenjoy/trunOut接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
		logger.info("======方法执行结束：wxenjoy/trunOut=======");
	}
	
	/**
	 * 转出接口数据检查
	 */
	private Map<String,Object> trunOutCheck(JSONObject paramMap) throws Exception{
		Map<String,Object> resMap = new HashMap<String,Object>();
		
		String finaceId = paramMap.getString("finaceId");
		String userId = paramMap.getString("userId");
		String turnOutAmount = paramMap.getString("turnOutAmount");//转出金额
		String passwordCash = paramMap.getString("passwordCash");//交易密码
//		String turnOutFee= paramMap.get("turnOutFee");//转出手续费
		if(StringUtils.isBlank(finaceId)){
			logger.error("转出接口数据检查失败：计划id为空");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}
		
//		if(StringUtils.isBlank(userId)){
//			logger.error("转出接口数据检查失败：用户id为空");
//			resMap.put("code", Consts.ERROR_CODE);
//			resMap.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
//			return resMap;
//		}
		
		if(StringUtils.isBlank(turnOutAmount)){
			logger.error("转出接口数据检查失败：转出金额为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.AMOUNT_IS_NULL);
			return resMap;
		}
		
		if (StringUtils.isBlank(passwordCash)) {
			logger.error("转出接口数据检查失败：交易密码为空");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", Message.CnDescriptionExpression.PAYPASSWORD_IS_NULL);
			return resMap;
		}
		
//		if (StringUtils.isBlank(turnOutFee)) {
//			logger.error("转出接口数据检查失败：转出手续费为空");
//			resMap.put("code", Consts.CHECK_CODE);
//			resMap.put("message", "转出手续费为空");
//			return resMap;
//
//		}
		
		// 转出金额检查
		boolean flag = turnOutAmount.matches("^[0-9]*[\\.]{0,1}[0-9]{0,2}$");
		if (!flag) {
			// 输入的值为非法字符
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message",
					Message.CnDescriptionExpression.BUYAMOUNT_IS_NON_STANDARD);
			return resMap;
		}

		BigDecimal turnOutAmountBD = new BigDecimal(turnOutAmount);// 转出金额
		
		if(turnOutAmountBD.compareTo(BigDecimal.ZERO) == 0 || turnOutAmountBD.compareTo(BigDecimal.ZERO) == -1 ){
			// 输入的值为非法字符
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message",
					Message.CnDescriptionExpression.BUYAMOUNT_IS_NON_STANDARD);
			return resMap;
		}
		
		// 判断提现支付密码是否正确
		User user = userService.getUserDetail(userId);
		if(!MD5.md5(passwordCash).equals(user.getPassword_cash())){
			logger.error("转出接口数据检查失败：交易密码错误");
			resMap.put("code", Consts.CHECK_CODE);
			resMap.put("message", "交易密码错误，请重新输入!");
			return resMap;
		}
		
		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}
	/**
	 * 查询用户的收益率
	 * @param
	 * @param response
	 */
	@RequestMapping(value = "/getYield")
	public void getYield(HttpServletRequest request, HttpServletResponse response) throws Exception{

		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}

		RequestHeader header = RequestUtil.decodeHeader(request); // 解密header
		Map<String,Object> 	paramsMap = RequestUtil.decodeData(request); // 解密请求参数

		//查询年利率的方法
		Map<String, Object> parmMap = new HashMap<String, Object>();//返回参数的map
		parmMap.put("userId", header.userId2String());
		parmMap.put("dayNum", paramsMap.get("dayNum"));
		parmMap.put("flag","1");
		Map<String, Object> jsonMap = new HashMap<String, Object>();//查询结果一个json的字符串

		//查询本金和收益（HX库）
		ResultDTO resultDto = turnOutService.getmoneyUserId(parmMap);//Action调ServiceImpl的方法
		ResponseUtil.write(response,resultDto);

	}


	/**
	 * 活期历史收益
	 */
	@RequestMapping(value = "/historyAmount")
	public void historyAmount(HttpServletRequest request, HttpServletResponse response) throws Exception{
		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}
		RequestHeader header = RequestUtil.decodeHeader(request);
		JSONObject paramMap = RequestUtil.decodeDataJson(request);

		String currentPageStr = paramMap.getString(Consts.Page.PAGE_CURRENT_NAME);//当前页
		String pageSizeStr = paramMap.getString(Consts.Page.PAGE_SIZE_NAME);//页大小
		Integer current = 1;
		Integer pageSize = 10;//默认显示10条
		//分页参数
		if (currentPageStr != null && !("".equals(currentPageStr))) {
			current = Integer.parseInt(currentPageStr);
		}
		if (pageSizeStr != null && !("".equals(pageSizeStr))) {
			pageSize = Integer.parseInt(pageSizeStr);
		}

		Map<String, Object> map = new HashMap<String,Object>();
		map.put("pageSize", String.valueOf(pageSize));
		map.put("current", String.valueOf(current));
		map.put("userId", header.getUserId());
		map.put("flag","2");
		// 查询余额宝历史收益列表
		ResultDTO result = turnOutService.queryAmountStatementList(map);
		ResponseUtil.write(response,  result);
	}
}
